(function () {
    "use strict";

    var url,
        loggedUser,
        $successMessage,
        $errorMessage;

    url = 'http://localhost:3000/';
    $successMessage = $('.messages .success');
    $errorMessage = $('.messages .error');

    function registerUser(user) {
        var urlReg = url + 'user';

        $.ajax({
            url: urlReg,
            type: 'POST',
            data: JSON.stringify(user),
            contentType: 'application/json',
            timeout: 5000,
            success: function () {
                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function loginUser(user) {
        var urlLogin = url + 'auth';

        return $.ajax({
            url: urlLogin,
            type: 'POST',
            data: JSON.stringify(user),
            contentType: 'application/json',
            timeout: 5000,
            success: function (user) {
                loggedUser = user.sessionKey;

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function logout(key) {
        var urlLogout = url + 'user';

        $.ajax({
            url: urlLogout,
            type: 'PUT',
            beforeSend: function (request)
            {
                request.setRequestHeader("X-SessionKey", loggedUser);
            },
            contentType: 'application/json',
            timeout: 5000,
            success: function () {
                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function submitPost(post) {
        var postUrl = url + 'post';

        return $.ajax({
            url: postUrl,
            type: 'POST',
                beforeSend: function (request)
                {
                    request.setRequestHeader("X-SessionKey", loggedUser);
                },
            data: JSON.stringify(post),
            contentType: 'application/json',
            timeout: 5000,
            success: function () {
                visualizePosts();

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function visualizePosts() {
        var postUrl = url + 'post';

        return $.ajax({
            url: postUrl,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    post,
                    $postList;

                $postList = $('<ul />');

                for (i = 0, len = data.length; i < len; i++) {
                    post = data[i];

                    $('<li />')
                        .append('User: ' + post.user.username + ', Title: ' + post.title + ', Message: ' + post.body)
                        .appendTo($postList);
                }

                $('#post-list-container').html($postList);

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function visualizePostsByUserName(user) {
        var postUrl = url + 'post?user=' + user;

        return $.ajax({
            url: postUrl,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    post,
                    $postList;

                $postList = $('<ul />');

                for (i = 0, len = data.length; i < len; i++) {
                    post = data[i];

                    $('<li />')
                        .append('User: ' + post.user.username + ', Title: ' + post.title + ', Message: ' + post.body)
                        .appendTo($postList);
                }

                $('#post-list-container').html($postList);

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function visualizePostsTitleSortedAscending() {
        var postUrl = url + 'post';

        return $.ajax({
            url: postUrl,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    post,
                    $postList;

                $postList = $('<ul />');

                data.sort(function (a, b) {
                    if (a.title < b.title)
                        return -1;
                    if (a.title > b.title)
                        return 1;
                    return 0;
                });

                for (i = 0, len = data.length; i < len; i++) {
                    post = data[i];

                    $('<li />')
                        .append('User: ' + post.user.username + ', Title: ' + post.title + ', Message: ' + post.body)
                        .appendTo($postList);
                }

                $('#post-list-container').html($postList);

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function visualizePostsTitleSortedDescending() {
        var postUrl = url + 'post';

        return $.ajax({
            url: postUrl,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    post,
                    $postList;

                $postList = $('<ul />');

                data.sort(function (a, b) {
                    if (a.title > b.title)
                        return -1;
                    if (a.title < b.title)
                        return 1;
                    return 0;
                });

                for (i = 0, len = data.length; i < len; i++) {
                    post = data[i];
                    $('<li />')
                        .append('User: ' + post.user.username + ', Title: ' + post.title + ', Message: ' + post.body)
                        .appendTo($postList);
                }

                $('#post-list-container').html($postList);

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function visualizePostsDateSortedAscending() {
        var postUrl = url + 'post';

        return $.ajax({
            url: postUrl,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    post,
                    $postList;

                $postList = $('<ul />');

                data.sort(function (a, b) {
                    return new Date(a.postDate) - new Date(b.postDate);
                });

                for (i = 0, len = data.length; i < len; i++) {
                    post = data[i];

                    $('<li />')
                        .append('User: ' + post.user.username + ', Title: ' + post.title + ', Message: ' + post.body + ', Date: ' + post.postDate)
                        .appendTo($postList);
                }

                $('#post-list-container').html($postList);

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function visualizePostsDateSortedDescending() {
        var postUrl = url + 'post';

        return $.ajax({
            url: postUrl,
            type: 'GET',
            contentType: 'application/json',
            timeout: 5000,
            success: function (data) {
                var len,
                    i,
                    post,
                    $postList;

                $postList = $('<ul />');

                data.sort(function (a, b) {
                    return new Date(b.postDate) - new Date(a.postDate);
                });

                for (i = 0, len = data.length; i < len; i++) {
                    post = data[i];

                    $('<li />')
                        .append('User: ' + post.user.username + ', Title: ' + post.title + ', Message: ' + post.body + ', Date: ' + post.postDate)
                        .appendTo($postList);
                }

                $('#post-list-container').html($postList);

                $successMessage
                    .html('Successfully executed!')
                    .show()
                    .fadeOut(2500);
            },
            error: function (error) {
                $errorMessage
                    .html('An error was provoked!')
                    .show()
                    .fadeOut(2500);
            }
        });
    }

    function showPostsInPages(count) {
        // TODO: not implemented
        throw Error('NotImplementedException');
    }

    (function($) {
        $('#button-register').on('click', function () {
            var user,
                hash,
                userName,
                userPassword,
                nameAndPass;

            userName = $('#input-register-user-name').val();
            userPassword = $('#input-register-user-password').val();
            nameAndPass = userName + userPassword;

            hash = CryptoJS.SHA1(nameAndPass) + '';

            user = {
                username: userName,
                authCode: hash
            };

            registerUser(user);
        });

        $('#button-login').on('click', function () {
            var user,
                hash,
                userName,
                userPassword,
                nameAndPass;

            userName = $('#input-login-user-name').val();
            userPassword = $('#input-login-user-password').val();
            nameAndPass = userName + userPassword;

            hash = CryptoJS.SHA1(nameAndPass) + '';

            user = {
                username: userName,
                authCode: hash
            };

            loginUser(user);
        });

        $('#button-logout').on('click', function () {
            logout();
        });

        $('#button-submit-post').on('click', function () {
            var post;

            post = {
                title: $('#input-submit-post-title').val(),
                body: $('#input-submit-post-body').val()
            };

            submitPost(post);
        });

        $('#button-filter-post-username').on('click', function () {
            var userPostlist;

            userPostlist = $('#input-filter-post-username').val();

            visualizePostsByUserName(userPostlist);
        });

        $('#button-sort-title-ascending').on('click', function () {
            visualizePostsTitleSortedAscending();
        });

        $('#button-sort-title-descending').on('click', function () {
            visualizePostsTitleSortedDescending();
        });

        $('#button-sort-date-ascending').on('click', function () {
            visualizePostsDateSortedAscending();
        });

        $('#button-sort-date-descending').on('click', function () {
            visualizePostsDateSortedDescending();
        });

        $('#button-show-posts-by-page').on('click', function () {
            var count;

            count = $('#input-posts-by-page').val();

            showPostsInPages(count);
        });
    }(jQuery));
}());